package com.liang.leetcode.binarytree.exercise;

import com.liang.leetcode.binarytree.entity.TreeNode;
import com.liang.leetcode.binarytree.util.BiTreeUtil;

import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.List;
import java.util.Queue;

/**
 * 二叉树的最小深度
 */
public class BiTree06_MinTreeDepth {

    public static void main(String[] args) {
        // 创建一棵二叉树
        List<Integer> nodeList = Arrays.asList(3, 9, 20, null, null, 15, 7);
        TreeNode root = BiTreeUtil.createBiTreeByRecursion(nodeList, 0);
        // 先序遍历这颗二叉树
        List<Integer> resultList = BiTreeUtil.preorderTraversal(root);
        System.out.println(resultList);
        int minDepth = minDepth(root);
        System.out.println("最小深度：" + minDepth);
    }

    /**
     * 111.二叉树的最小深度
     */
    // 递归：处理左右孩子不为空的逻辑
    public static int minDepth(TreeNode root) {
        if (root == null) {
            return 0;
        }
        int leftDepth = minDepth(root.left);
        int rightDepth = minDepth(root.right);
        if (root.left == null && root.right != null) {
            return rightDepth + 1;
        }
        if (root.right == null && root.left != null) {
            return leftDepth + 1;
        }
        return Math.min(leftDepth, rightDepth) + 1;
    }

    // 迭代：层序遍历
    public static int minDepth2(TreeNode root) {
        if (root == null) {
            return 0;
        }
        int depth = 0;
        Queue<TreeNode> queue = new ArrayDeque<>();
        queue.offer(root);
        while (!queue.isEmpty()) {
            depth++;
            int size = queue.size();
            for (int i = 0; i < size; i++) {
                TreeNode node = queue.poll();
                // 当节点左右孩子都为空的时候，说明是最低点的一层了，退出
                if (node.left == null && node.right == null) {
                    return depth;
                }
                if (node.left != null) {
                    queue.offer(node.left);
                }
                if (node.right != null) {
                    queue.offer(node.right);
                }
            }
        }
        return depth;
    }

}
